package com.zhihu.service.impl;

import com.zhihu.client.AnswerClient;
import com.zhihu.client.QuestionClient;
import com.zhihu.dao.AnswerRepository;
import com.zhihu.dao.QuestionRepository;
import com.zhihu.pojo.Answer;
import com.zhihu.pojo.OpusCommNums;
import com.zhihu.pojo.Question;
import com.zhihu.pojo.baseVo.BaseResult;
import com.zhihu.pojo.req.AnswerReq;
import com.zhihu.pojo.req.QuestionReq;
import com.zhihu.service.OpnRedisService;
import com.zhihu.utils.RedisKeyUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class OpnRedisServiceImpl implements OpnRedisService {

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    QuestionClient questionClient;

    @Autowired
    QuestionRepository questionRepository;

    @Autowired
    AnswerRepository answerRepository;

    @Autowired
    AnswerClient answerClient;

    //将已发布的作品类型id和id 拼接成key值
    @Override
    public void savePublishedOpusRedis(String opusTap, String opusId) {
        String key = RedisKeyUtils.getPublishedOpusKey(opusTap, opusId);
        redisTemplate.opsForHash().put(RedisKeyUtils.MAP_OPUS_KEY, key,0);
    }

    //获取已发布作品的评论数
    @Override
    public Integer getOpusCommNumsFromRedis(String opusTap, String opusId) {
        String key = RedisKeyUtils.getPublishedOpusKey(opusTap, opusId);
        if (key!=null) {
            Integer quesCommNums = Integer.valueOf(redisTemplate.opsForHash().get(RedisKeyUtils.MAP_OPUS_KEY, key).toString());
            System.out.println(quesCommNums);
            return quesCommNums;
        }
        return 0;
    }

    //作品的评论数增加1
    @Override
    public void incrementOpusCommNums(String opusTap, String opusId) {
        String key = RedisKeyUtils.getPublishedOpusKey(opusTap, opusId);
        redisTemplate.opsForHash().increment(RedisKeyUtils.MAP_OPUS_KEY, key, 1);
    }

    //作品的评论数减少1
    @Override
    public void decrementOpusCommNums(String opusTap, String opusId) {
        String key = RedisKeyUtils.getPublishedOpusKey(opusTap, opusId);
        redisTemplate.opsForHash().increment(RedisKeyUtils.MAP_OPUS_KEY, key, -1);
    }

    //获取redis中所有作品与评论数的数据
    @Override
    public List<OpusCommNums> getCommNumsDataFromRedis() {
        Cursor<Map.Entry<Object, Object>> cursor = redisTemplate.opsForHash().scan(RedisKeyUtils.MAP_OPUS_KEY, ScanOptions.NONE);
        List<OpusCommNums> list = new ArrayList<>();
        while (cursor.hasNext()) {
            Map.Entry<Object, Object> entry = cursor.next();
            String key = (String) entry.getKey();
            //分离出 opusTap，opusId
            String[] split = key.split("::");
            String opusTap = split[0];
            String opusId = split[1];

            Integer commNums = (Integer) entry.getValue();

            //组装成 LikeOpus 对象
            OpusCommNums opusCommNums = new OpusCommNums(opusTap, opusId, commNums);
            list.add(opusCommNums);

            //存到 list 后从 Redis 中删除
            //redisTemplate.opsForHash().delete(RedisKeyUtils.MAP_USER_OPUS_LIKED, key);
        }
        return list;
    }

    //将redis中的作品的评论数同步更新到数据库中
    @Override
    public void updateCommNumsToMysql() {
        List<OpusCommNums> commNumsDataFromRedis = this.getCommNumsDataFromRedis();
        if (commNumsDataFromRedis!=null){
            for (OpusCommNums opusCommNums:commNumsDataFromRedis) {
                if (opusCommNums.getOpusTap().equals("1")){
                    BaseResult baseResult = questionClient.findQuestionById(Integer.valueOf(opusCommNums.getOpusId()));
                    if (baseResult.getCode()==0){
                        System.out.println(baseResult.getMsg());
                        QuestionReq questionReq = (QuestionReq)baseResult.getData();
                        if (questionReq!=null){
                            Question question = new Question();
                            //将redis中该问题的评论总数 封装到questionReq的getCommNums字段中
                            Integer commNums = opusCommNums.getCommNums();
                            questionReq.setQuesCommNums(commNums);
                            //将接收的questionReq实体转换为question
                            BeanUtils.copyProperties(questionReq,question);
                            //更新问题的评论数量到数据库中
                            questionRepository.saveAndFlush(question);
                        }else {
                            System.out.println("问题已被删除！");
                        }
                    }else {
                        System.out.println(baseResult.getMsg());
                    }
                }
                if (opusCommNums.getOpusTap().equals("2")){
                    BaseResult baseResult = answerClient.findAnswerById(Integer.valueOf(opusCommNums.getOpusId()));
                    if (baseResult.getCode()==0){
                        System.out.println(baseResult.getMsg());
                        AnswerReq answerReq = (AnswerReq)baseResult.getData();
                        if (answerReq!=null){
                            Answer answer = new Answer();
                            //将redis中该回答的评论总数 封装到answerReq的getCommNums字段中
                            Integer commNums = opusCommNums.getCommNums();
                            answerReq.setAnsCommNums(commNums);
                            //将接收的answerReq实体转换为answer
                            BeanUtils.copyProperties(answerReq,answer);
                            //更新回答的评论数量到数据库中
                            answerRepository.saveAndFlush(answer);
                        }else {
                            System.out.println("该问题已经被删除");
                        }
                    }else {
                        System.out.println(baseResult.getMsg());
                    }
                }
            }
        }
    }
}
